package org.muxiao.seckill.rabbitmq;

import cn.hutool.json.JSONUtil;
import lombok.extern.slf4j.Slf4j;
import org.muxiao.seckill.pojo.SeckillMessage;
import org.muxiao.seckill.pojo.User;
import org.muxiao.seckill.service.GoodsService;
import org.muxiao.seckill.service.OrderService;
import org.muxiao.seckill.vo.GoodsVo;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

import static org.muxiao.seckill.config.RabbitMQSecKillConfig.QUEUE_SECKILL;

/**
 * MQReceiverMessage: 消息的接收者/消费者, 这里调用seckill方法()
 */
@Service
@Slf4j
public class MQReceiverMessage {

    /**
     * 注入 GoodsService 对象, 用于查询秒杀商品信息
     */
    @Resource
    private GoodsService goodsService;

    /**
     * 注入 OrderService 对象, 用于完成秒杀下单操作
     */
    @Resource
    private OrderService orderService;

    /**
     * 接收MQ消息, 解析消息, 并完成下单
     *
     * @param message
     */
    @RabbitListener(queues = {QUEUE_SECKILL})
    public void receiveMessage(String message) {
        log.info("接收到消息-->" + message);

        //使用 hutool 依赖, 解析消息为 SeckillMessage 对象
        SeckillMessage seckillMessage = JSONUtil.toBean(message, SeckillMessage.class);
        //取出秒杀用户对象
        User user = seckillMessage.getUser();
        //取出秒杀的商品id
        Long goodsId = seckillMessage.getGoodsId();
        //通过商品id,得到对应的GoodsVo
        GoodsVo goodsVo = goodsService.findGoodsVoByGoodsId(goodsId);

        //进行秒杀下单操作
        orderService.secKill(user, goodsVo);
    }
}
